package org.alwayssuper.protocol.gbt32960;

import org.alwayssuper.protostar.annotation.Field;
import org.alwayssuper.protostar.annotation.Message;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.alwayssuper.protocol.basics.GBTMessage;
import org.alwayssuper.protocol.commons.GBTRequestType;

import java.time.LocalDateTime;

/**
 * G0B 数据单元加密密钥交换
 * 支持GB/T 32960.3-2016 (version=0) 和 GB/T 32960.3-2025 (version=1) 两个版本
 * 
 * 用于车辆与平台之间进行加密密钥交换
 * 支持RSA、AES、SM2、SM4等加密算法
 * 
 * @author alwaysSuper
 */
@ToString
@Data
@Accessors(chain = true)
@Message(GBTRequestType.数据单元加密密钥交换)
public class G0B extends GBTMessage {
    @Field(length = 1, desc = "密钥类型:0x02:RSA算法;0x03:AES128算法;0x04:SM2算法;0x05:SM4算法")
    private int keyType;
    
    //密钥长度:密钥总字节数N,有效值范围1~65531 由encryptionKey中的lengthUnit获取
    private int keyLength;
    
    @Field(lengthUnit = 2, desc = "密钥:数据单元加密密钥,长度由keyLength确定")
    private byte[] encryptionKey;
    
    @Field(length = 6, desc = "启用时间(YYMMDDHHMMSS):密钥启用时间")
    private LocalDateTime enableTime;
    
    @Field(length = 6, desc = "失效时间(YYMMDDHHMMSS):密钥失效时间")
    private LocalDateTime expireTime;

    public int getkeyLength() {
        return encryptionKey == null ? 0 : encryptionKey.length;
    }
    
    // 密钥类型常量定义
    public static final int KEY_TYPE_RSA = 0x02;
    public static final int KEY_TYPE_AES128 = 0x03;
    public static final int KEY_TYPE_SM2 = 0x04;
    public static final int KEY_TYPE_SM4 = 0x05;
    
    /**
     * 检查密钥是否在有效期内
     * @param currentTime 当前时间
     * @return true: 有效, false: 无效
     */
    public boolean isKeyValid(LocalDateTime currentTime) {
        if (enableTime == null || expireTime == null || currentTime == null) {
            return false;
        }
        return !currentTime.isBefore(enableTime) && currentTime.isBefore(expireTime);
    }
    
    /**
     * 获取密钥类型描述
     * @return 密钥类型描述字符串
     */
    public String getKeyTypeDescription() {
        switch (keyType) {
            case KEY_TYPE_RSA:
                return "RSA算法";
            case KEY_TYPE_AES128:
                return "AES128算法";
            case KEY_TYPE_SM2:
                return "SM2算法";
            case KEY_TYPE_SM4:
                return "SM4算法";
            default:
                return "未知类型(" + keyType + ")";
        }
    }
}